import { defineStore } from "pinia";

export const useEditorStore = defineStore("editor", {
  state: () => ({
    //初始化空列表
    valueHtml: "",
    editPost: {
      id: 0,
      source: 0,
      title: "",
      content: "",
      pics: [],
    },

    editableTabs: [
      {
        title: "新文章",
        name: "1",
        id: 0,
        source: 0,
        longTitle: "",
        content: "",
        pics: [],
        // content: '写点什么呢？',
      },
    ],
    editableTabsValue: "1",
    tabIndex: 1,
  }),
  getters: {
    getEditPost: (state) => {
      return state.editPost;
    },
  },
  actions: {
    copyItem2EditPost(item) {
      const content = `<h1>${item.title}</h1> <p>${item.content}</p>`;
      this.valueHtml = content;
      // this.editPost.id = 0;
      this.editPost.source = item.id;
      this.editPost.title = item.title;
      this.editPost.content = item.content;
      //   console.log(this.editPost);
    },
    setEditPostId(id) {
      this.editPost.id = id;
    },
    setEditPostContent(content) {
      this.editPost.content = content;
    },
    setEditPostTitle(title) {
      this.editPost.title = title;
    },

    setEditPost(post) {
      this.editPost = JSON.parse(post);
      console.log(this.editPost);
    },

    addTab(item = { title: "New Tab", content: "New Tab content" }) {
      //如果标签页打开过，直接高亮显示对应的标签页
      item.longTitle = item.title;
      const isTabOpen = (element) => element.longTitle === item.title;
      const tabIndex = this.editableTabs.findIndex(isTabOpen);
      if (tabIndex >= 0) {
        this.editableTabsValue = this.editableTabs.at(tabIndex).name;
        return;
      }
      //如果没有打开过，继续执行
      const newTabName = `${++this.tabIndex}`;
      item.name = newTabName;
      const content = `<h1>${item.title}</h1> <p>${item.content}</p>`;
      // this.valueHtml = content;
      item.source = item.id;

      if (item.title.length > 4) {
        item.title = item.title.substring(0, 4) + "...";
      } else {
        item.title = item.title;
      }
      item.content = content;
      this.editableTabs.push(item);
      this.editableTabsValue = newTabName;
    },

    closeTab(targetName) {
      if (this.editableTabs.length === 1) {
        return 
      }
      const tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }

      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter((tab) => tab.name !== targetName);
    },
  },
});
